﻿using SD.Infrastructure.Repository.EntityFrameworkCore;
using SD.Infrastructure.RepositoryBase;
using SlamDunk.MES.Domain.Entities.ConfigurationContext;
using SlamDunk.MES.Domain.IRepositories.Interfaces.ConfigurationContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SlamDunk.MES.Repository.Implements.ConfigurationContext
{
    /// <summary>
    /// 工作通知仓储实现
    /// </summary>
    public class NotificationRepository : EFAggRootRepositoryProvider<Notification>, INotificationRepository
    {
        #region # 分页获取工作通知列表 —— ICollection<Notification> FindByPage(string keywords...
        /// <summary>
        /// 分页获取工作通知列表
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="facilityIds">工厂模型Id集</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>工作通知列表</returns>
        public ICollection<Notification> FindByPage(string keywords, IList<Guid> facilityIds, DateTime? startTime, DateTime? endTime, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            Expression<Func<Notification, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(keywords) || x.Keywords.Contains(keywords)) &&
                    (startTime == null || x.IssuedDate >= startTime) &&
                    (endTime == null || x.IssuedDate <= endTime);

            IQueryable<Notification> notifications = base.Find(condition);
            if (facilityIds != null && facilityIds.Any())
            {
                notifications = notifications.Where(x => x.FacilityId.HasValue && facilityIds.Contains(x.FacilityId.Value));
            }

            IOrderedQueryable<Notification> orderedResult = notifications.OrderByDescending(x => x.IssuedDate).ThenByDescending(x => x.Priority);
            IQueryable<Notification> pagedResult = orderedResult.ToPage(pageIndex, pageSize, out rowCount, out pageCount);

            return pagedResult.ToList();
        }
        #endregion
    }
}
